//
//  TitleViewController.m
//  SinaWebo
//
//  Created by 王方伟 on 2017/1/17.
//  Copyright © 2017年 亦心. All rights reserved.
//

#import "TitleViewController.h"
#import "TitlePresentationController.h"
#import "HomeStatusService.h"
#import "TitleHeadView.h"
#import "TitleViewCell.h"
#import "AllGroups.h"


@interface TitleViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) NSArray *dataSource;
@end

@implementation TitleViewController
static NSString * const ID = @"TitleViewCell";
static NSString * const HEAD_ID = @"TitleHeadView";

- (NSArray *)dataSource{
    if (_dataSource == nil) {
        _dataSource = [NSArray array];
    }
    return _dataSource;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupTableView];
    
    [self getAllGroups];
}

- (void)setupTableView{
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.tableView.rowHeight = 44;
    self.tableView.sectionHeaderHeight = 0;
    self.tableView.sectionFooterHeight = 0;
    self.tableView.contentInset = UIEdgeInsetsMake(-25, 0, 0, 0);
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([TitleViewCell class]) bundle:nil] forCellReuseIdentifier:ID];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([TitleHeadView class]) bundle:nil] forHeaderFooterViewReuseIdentifier:HEAD_ID];
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataSource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.dataSource[section] group].count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) return 0;
    return 20;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    TitleHeadView *headView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HEAD_ID];
    headView.model = _dataSource[section];
    return headView;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    TitleViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID forIndexPath:indexPath];
    cell.model = [_dataSource[indexPath.section] group][indexPath.row];
    return cell;
}

- (void)getAllGroups{
    AllGroupRequest *request = [AllGroupRequest request];
    [HomeStatusService getAllGrousDataWith:request success:^(AllGroupResponse *response) {
        self.dataSource = [self removeEmptyGroup:response.groups];
        [self.tableView reloadData];
    } failure:nil];
}

- (NSArray *)removeEmptyGroup:(NSArray *)dataArray{
    NSMutableArray *array = [NSMutableArray array];
    for (AllGroups *groups in dataArray) {
        if (groups.group.count) {
            [array addObject:groups];
        }
    }
    return [array copy];
    
}

@end
